package org.xp.judgeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xp.judgeplatform.exception.BusinessException;
import org.xp.judgeplatform.mapper.ChatMessageMapper;
import org.xp.judgeplatform.mapper.ChatSessionMapper;
import org.xp.judgeplatform.mapper.UserMapper;
import org.xp.judgeplatform.pojo.dto.ChatDTO.ChatSendMessageDTO;
import org.xp.judgeplatform.pojo.entity.ChatMessage;
import org.xp.judgeplatform.pojo.entity.ChatSession;
import org.xp.judgeplatform.pojo.entity.User;
import org.xp.judgeplatform.service.ChatService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
@AllArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatSessionMapper chatSessionMapper;
    private final ChatMessageMapper chatMessageMapper;
    private final UserMapper userMapper;

    @Override
    public List<ChatSession> getUserSessions(Integer userId) {
        log.info("获取用户会话列表: userId={}", userId);

        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                    .orderByDesc("updated_at");

        return chatSessionMapper.selectList(queryWrapper);
    }

    @Override
    public List<ChatMessage> getSessionMessages(String sessionId) {
        log.info("获取会话消息列表: sessionId={}", sessionId);

        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                .orderByAsc("created_at");

        return chatMessageMapper.selectList(queryWrapper);
    }

    @Override
    public String sendMessage(ChatSendMessageDTO sendMessageDTO) {
        log.info("保存聊天消息: 用户ID={}, 会话ID={}, 内容={}",
                sendMessageDTO.getUserId(), sendMessageDTO.getSessionId(), sendMessageDTO.getContent());

        // 验证用户是否存在
        User user = userMapper.selectById(sendMessageDTO.getUserId());

        if(user == null){
            log.error("用户不存在: userId={}", sendMessageDTO.getUserId());
            throw new BusinessException(404, "用户不存在");
        }

        String sessionId = sendMessageDTO.getSessionId();

        // 检查会话是否存在，不存在则创建
        ChatSession session = getOrCreateSession(sessionId, sendMessageDTO.getUserId(), sendMessageDTO.getTitle(), user.getUsername());
        sessionId = session.getSessionId();

        // 保存用户消息
        ChatMessage userMessage = new ChatMessage();
        userMessage.setMessageId(UUID.randomUUID().toString());
        userMessage.setSessionId(sessionId);
        userMessage.setUserId(sendMessageDTO.getUserId());
        userMessage.setIsAi(false); // 用户消息
        userMessage.setContent(sendMessageDTO.getContent());
        userMessage.setCreatedAt(LocalDateTime.now());

        int result = chatMessageMapper.insert(userMessage);
        if (result > 0) {
            // 更新会话消息数量和时间
            updateSessionAfterMessage(sessionId);
            log.info("用户消息保存成功: messageId={}", userMessage.getMessageId());
            return sessionId;
        } else {
            log.error("用户消息保存失败: userId={}, sessionId={}", sendMessageDTO.getUserId(), sessionId);
            throw new BusinessException(500, "消息保存失败");
        }

    }

    @Override
    public void saveAIReply(String sessionId, String content) {
        log.info("保存AI回复: sessionId={}, contentLength={}", sessionId, content.length());

        // 保存AI回复消息
        ChatMessage aiMessage = new ChatMessage();
        aiMessage.setMessageId(UUID.randomUUID().toString());
        aiMessage.setSessionId(sessionId);
        aiMessage.setUserId(null); // AI消息没有用户ID
        aiMessage.setIsAi(true); // AI消息
        aiMessage.setContent(content);
        aiMessage.setCreatedAt(LocalDateTime.now());

        int result = chatMessageMapper.insert(aiMessage);
        if (result > 0) {
            // 更新会话消息数量和时间
            updateSessionAfterMessage(sessionId);
            log.info("AI回复保存成功: messageId={}", aiMessage.getMessageId());
        } else {
            log.error("AI回复保存失败: sessionId={}", sessionId);
            throw new BusinessException(500, "AI回复保存失败");
        }
    }

    @Override
    public void deleteSession(String sessionId, Integer userId) {
        log.info("删除会话: sessionId={}, userId={}", sessionId, userId);

        // 验证会话是否属于该用户
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                .eq("user_id", userId);

        ChatSession session = chatSessionMapper.selectOne(queryWrapper);
        if (session == null) {
            log.warn("会话不存在或不属于该用户: sessionId={}, userId={}", sessionId, userId);
            throw new BusinessException(404, "会话不存在或无权限删除");
        }

        // 物理删除会话（级联删除消息）
        int result = chatSessionMapper.deleteById(session.getId());
        if (result > 0) {
            log.info("会话删除成功: sessionId={}", sessionId);
        } else {
            log.error("会话删除失败: sessionId={}", sessionId);
            throw new BusinessException(500, "会话删除失败");
        }
    }

    @Override
    public void updateSessionTitle(String sessionId, String title) {
        log.info("更新会话标题: sessionId={}, title={}", sessionId, title);

        UpdateWrapper<ChatSession> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("session_id", sessionId)
                .set("title", title)
                .set("updated_at", LocalDateTime.now());

        int result = chatSessionMapper.update(null, updateWrapper);
        if (result > 0) {
            log.info("会话标题更新成功: sessionId={}, title={}", sessionId, title);
        } else {
            log.warn("会话标题更新失败，可能会话不存在: sessionId={}", sessionId);
            throw new BusinessException(404, "会话不存在");
        }
    }

    // 验证会话是否存在
    private ChatSession getOrCreateSession(String sessionId, Integer userId, String title, String username) {
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            // 获取现有会话
            QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("session_id", sessionId);
            ChatSession existingSession = chatSessionMapper.selectOne(queryWrapper);
            if (existingSession != null) {
                log.info("找到现有会话: sessionId={}", sessionId);
                return existingSession;
            }
        } else {
            // 不存在就生成新的会话ID
            sessionId = UUID.randomUUID().toString();
        }

        // 创建新会话
        ChatSession newSession = new ChatSession();
        newSession.setSessionId(sessionId);
        newSession.setUserId(userId);

        // 设置会话标题
        if (title != null && !title.trim().isEmpty()) {
            newSession.setTitle(title.trim());
        } else {
            newSession.setTitle("新对话 - " + username);
        }

        newSession.setMessageCount(0);
        newSession.setCreatedAt(LocalDateTime.now());
        newSession.setUpdatedAt(LocalDateTime.now());

        int result = chatSessionMapper.insert(newSession);
        if (result > 0) {
            log.info("新会话创建成功: sessionId={}, userId={}, title={}",
                    sessionId, userId, newSession.getTitle());
            return newSession;
        } else {
            log.error("新会话创建失败: sessionId={}, userId={}", sessionId, userId);
            throw new BusinessException(500, "会话创建失败");
        }
    }

    // 更新会话的消息数量和更新时间
    private void updateSessionAfterMessage(String sessionId) {
        // 统计会话消息总数
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId);
        Long messageCount = chatMessageMapper.selectCount(queryWrapper);

        // 更新会话信息
        UpdateWrapper<ChatSession> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("session_id", sessionId)
                .set("message_count", messageCount)
                .set("updated_at", LocalDateTime.now());

        int result = chatSessionMapper.update(null, updateWrapper);
        if (result > 0) {
            // DEBUG级别：会话更新成功（非关键业务流程）
            log.debug("会话信息更新成功: sessionId={}, messageCount={}", sessionId, messageCount);
        } else {
            // WARN级别：更新失败但不影响主流程
            log.warn("会话信息更新失败: sessionId={}", sessionId);
        }
    }
}
